#include "log.h"


uulogging* uulogging::pinstance = NULL;
cmutex uulogging::loglock_;

uulogging::uulogging():f(NULL){
  Initialize();
}

uulogging::~uulogging(){
  fclose(f);
}

uulogging& uulogging::R(){
  if (pinstance==NULL){
    cguard g(loglock_);
    if (pinstance==NULL){
      pinstance = new uulogging();
    }
  }
  return *pinstance;
}

//http://stackoverflow.com/questions/11655003/localtime-returns-gmt-for-windows-programs-running-on-cygwin-shells
/*** Initialize the object*/
void uulogging::Initialize(){
  char buf[128]="tt-";
  const size_t sz = sizeof("2014-00-00");
  const size_t sz2 = strlen("tt-");
  {
    time_t timer;
    struct tm* tm_info;
    time(&timer);
    tm_info = localtime(&timer);
    strftime(buf+sz2, sz, "%Y-%m-%d", tm_info);
  }
  strcat(buf,".lst");
  f=fopen(buf,"a+");
  //setbuf(f,NULL);
  setvbuf(f,NULL,_IONBF,0);//TLPI p237
}

#include "util.h"

void uulogging::Printf2File(const char *format, ...){
  cguard g(loglock_);

  char buf[1024]={0};
#if 1
  static const size_t sz = sizeof("0000-00-00 00:00:00");
  {
    static time_t timer;
    time(&timer);
    struct tm* tm_info= localtime(&timer);
    strftime(buf, sz, "%Y-%m-%d %H:%M:%S", tm_info);
  }
#else
  string ct=curtime();
  size_t sz=ct.size();
  memcpy(buf,&ct[0],sz*sizeof(char*));
#endif

  buf[sz-1] = ' ';
  va_list args;
  va_start(args, format);
  vsnprintf(buf+sz, 1024, format, args);
  fwrite(buf, sizeof(char), strlen(buf),f);
  va_end(args);
}